package de.gbeine.java.depview.graph;

import java.util.Set;

import lombok.extern.slf4j.Slf4j;
import de.gbeine.java.depview.model.Element;
import de.gbeine.java.depview.model.Package;
import de.gbeine.java.depview.model.Class;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.Graph;

@Slf4j
class ClassGraph implements GraphConverter {

    public static final ClassGraph INSTANCE = new ClassGraph();

    private ClassGraph() {
        super();
    }

    @Override
    public Graph<Element, Number> createGraph(final Set<Package> pModel, final Filter pFilter) {
        final Dependencies dependencies = new Dependencies();
        final Graph<Element, Number> graph = new DirectedSparseMultigraph<Element, Number>();
        int counter = 0;
        for (final Package pkg : pModel) {
            if (pFilter.isFiltered(pkg)) {
                ClassGraph.log.debug("Not adding package {} - it is filtered", pkg.getName());
                continue;
            }
            ClassGraph.log.debug("Try to add package {}", pkg.getName());
            for (final Class clazz : pkg.getClasses()) {
                if (pFilter.isFiltered(clazz)) {
                    ClassGraph.log.debug("Not adding clazz {} - it is filtered", clazz.getName());
                    continue;
                }
                ClassGraph.log.debug("Found class {}", clazz.getName());
                for (final Class dep : clazz.outboundDependencies()) {
                    if (!pFilter.isFiltered(dep) && !dependencies.dependencyExists(clazz, dep)) {
                        dependencies.addDependency(clazz, dep);
                        graph.addEdge(counter, clazz, dep);
                        counter++;
                    }
                }
            }
        }
        return graph;
    }

}
